<template>
  <el-dialog :title="!dataForm.id ?  '不合格品新增': '不合格品修改'" :close-on-click-modal="false" :visible.sync="visible" fullscreen center>
    <el-button class="miui-dialog-close-btn" @click="visible = false">关闭页面</el-button>
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm" label-width="90px">
      <el-row>
        <el-col :span="12" v-if="userInfo.lessDeptId == '1'">
          <el-form-item label="申报部门" prop="deptId">
            <el-select v-model="dataForm.deptId" placeholder="请选择" @change="deptNameChange($event)" clearable>
              <el-option v-for="item in deptOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12" v-else>
          <el-form-item label="申报部门">
            <el-input v-model="userInfo.lessDeptName" disabled style="width: 197px;"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="申报仓库" prop="stockId">
            <el-select v-model="dataForm.stockId" placeholder="请选择" clearable>
              <el-option v-for="item in stockOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="责任人" prop="dutyUser">
            <el-select v-model="dataForm.dutyUser" filterable clearable>
              <el-option v-for="item in userOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <el-form :inline="true">
      <el-form-item>
        <el-button type="primary" @click="openTableList('single')">单品添加商品</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="barcodeScan()">条码扫描</el-button>
      </el-form-item>
      <el-form-item style="float: right;">
        <el-button type="danger" @click="delTableData">删除</el-button>
      </el-form-item>
      <el-table :data="dataList" border v-loading="dataListLoading" show-summary :summary-method="getSummaries"
        @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="40"></el-table-column>
        <el-table-column prop="goodsCode" label="商品编号" min-width="130"></el-table-column>
        <el-table-column prop="viewGoodsName" label="商品名称" min-width="240"></el-table-column>
        <el-table-column prop="reason1" label="不合格品原因">
          <template slot-scope="scope">
            <el-select v-model="scope.row.reason1" placeholder="请选择原因" @change="getSecondReasonList">
              <el-option v-for="item in reasonOption" :key="item.value" :label="item.label" :value="item.value"></el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column prop="reason2" label="不合格品现象">
          <template slot-scope="scope">
            <el-select v-model="scope.row.reason2" placeholder="请选择现象" @change="reason2Change($event,scope.row)">
              <el-option v-for="item in reasonSecondOption" :key="item.value" :label="item.label" :value="item.value"></el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="备注">
          <template slot-scope="scope">
            <el-input v-model="scope.row.memo" style="text-align: center;"></el-input>
          </template>
        </el-table-column>
        <el-table-column label="数量">
          <template slot-scope="scope">
            <el-form-item :prop="'detailList.' + scope.$index + '.goodsQuantity'" :rules="dataRule.goodsQuantity"
              label-width="0px">
              <el-input v-model="scope.row.goodsQuantity" :ref="'number'+scope.$index" @keyup.enter.native="enterChange(scope.$index)"></el-input>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column prop="handleMenthod" label="处理">
          <template slot-scope="scope">
            <el-select v-model="scope.row.handleMenthod" placeholder="请选择处理方式">
              <el-option label="报残" value="1"></el-option>
              <el-option label="退回" value="2"></el-option>
            </el-select>
          </template>
        </el-table-column>
      </el-table>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">关闭</el-button>
      <el-button type="primary" @click="dataFormSubmit" :loading="ischeck" v-prevent-re-click>保存</el-button>
      <el-switch v-model="dataForm.status" active-text="保存并审核" inactive-value="0" active-value="1" style="margin-left: 15px;"></el-switch>
      <el-switch v-if="dataForm.status == '1'" v-model="dataForm.autoStatus" active-text="是否生成调拨单" inactive-value="0"
        active-value="1" style="margin-left: 15px;"></el-switch>
    </span>
    <bill-list v-if="singleListVisible" ref="billOrSingle" @showBrandList="getBrandData"></bill-list>
    <order-detail v-if="detailVisible" ref="detailDialog"></order-detail>
    <barcode-scan v-if="barcodeVisible" ref="barcodeDialog" @refreshData="getBarcodeGoodsData"></barcode-scan>
  </el-dialog>
</template>


<script>
  import { mapGetters } from "vuex"
  import * as check from '@/util/check/check'
  import {
    editUnqualifiedObj,
    getUnqualifiedById,
    addUnqualifiedObj
  } from "@/api/eims/unqualified"
  import { getStockList } from "@/api/eims/stock"
  import { fetchTree, getDeptInfo } from "@/api/admin/dept"
  import { getUserListNoRole } from "@/api/admin/user"
  import { getUnqualifiedReasonList } from "@/api/eims/unqualifiedreason"

  import BillList from "@/components/business/GoodsStorage"
  import OrderDetail from "./detail"
  import BarcodeScan from '@/components/business/BarcodeScan'

  export default {
    data() {
      return {
        ischeck: false,
        visible: false,
        singleListVisible: false,
        detailVisible: false,
        barcodeVisible: false,
        dataListLoading: false,
        dataForm: {
          status: "0", // 是否审核 0-未审核,1-已审核,2-已处理
          autoStatus: "0", // 是否生成调拨单(1-是,0-否)
          billId: "", // 调拨单号
          deptId: "", // 申报部门
          deptName: "", // 申报部门名称
          stockId: "", // 申报仓库
          stockName: "", // 申报仓库
          createUser: "", //  制单人
          dutyUser: "", //  责任人
          detailList: []
        },
        // verify: false,
        dataList: [],
        deptOptions: [],
        userOptions: [],
        stockOptions: [],
        selectionList: [],
        reasonOption: [],
        reasonSecondOption: [],
        dataRule: {
          deptId: [{
            required: true,
            message: "申报部门不能为空"
          }],
          stockId: [{
            required: true,
            message: "申报仓库不能为空"
          }],
          goodsQuantity: [{
            validator: check.checkIsNumber,
            trigger: 'blur'
          }]
        }
      };
    },
    components: {
      BillList,
      //OrderDetail
      BarcodeScan
    },
    computed: {
      ...mapGetters(["permissions", "userInfo"])
    },
    methods: {
      init(id) {
        this.dataForm.detailList = []
        this.dataList = []
        this.dataForm.stockId = ""
        this.stockOptions = []
        this.dataForm.id = id || 0
        this.visible = true
        this.$nextTick(() => {
          this.$refs["dataForm"].resetFields()
          this.getDeptList()
          this.getUserList()
          this.getParentReasonList()
          if (this.dataForm.id) {
            this.dataListLoading = true
            getUnqualifiedById(this.dataForm.id).then(response => {
              if(response.data.code == '0'){
                this.dataForm = response.data.data
                this.dataList = response.data.data.detailList
                this.getOutStockList(this.dataForm.deptId)
                this.dataListLoading = false
                this.dataList.forEach(item => {
                  this.getSecondReasonList(item.reason1)
                })
              }else{
                this.$message.error(response.data.msg)
              }
            })
          }
        })
      },
      deptNameChange($event) {
        this.deptOptions.forEach(item => {
          if (item.value == $event) {
            this.dataForm.deptName = item.label;
          }
        });
        this.getOutStockList($event);
      },
      stockNameChange($event) {
        this.stockOptions.forEach(item => {
          if (item.value == $event) {
            this.dataForm.stockName = item.label;
          }
        });
      },
      //  回车切换下一行商品数量
      enterChange(index) {
        if (this.$refs['number' + (index * 1 + 1)]) {
          this.$refs['number' + (index * 1 + 1)].focus()
        }
      },
      // 获取员工用户列表
      getUserList(id) {
        getUserListNoRole({unitId: id}).then(response => {
          if(response.data.code == '0'){
            let resultData = response.data.data
            let userList = []
            resultData.forEach(item => {
              let userObj = {
                value: item.id,
                label: item.realName + '(' + item.workNumber + ')'
              }
              userList.push(userObj)
            })
            this.userOptions = userList
          }else{
            this.$message.error(response.data.msg)
          }
        })
      },
      // 获取部门列表
      getDeptList() {
        if (this.userInfo.lessDeptId == '1') {
          getDeptInfo().then(response => {
            if(response.data.code == '0'){
              let deptList = []
              let resultData = response.data.data
              resultData.forEach(item => {
                let deptObj = {
                  value: item.id,
                  label: item.name
                }
                deptList.push(deptObj)
              })
              this.deptOptions = deptList
            }else{
              this.$message.error(response.data.msg)
            }
          })
        } else {
          this.dataForm.deptId = this.userInfo.lessDeptId
          this.dataForm.deptName = this.userInfo.lessDeptName
          this.getOutStockList(this.userInfo.lessDeptId)
        }
      },
      // 获取库仓位列表
      getOutStockList(id) {
        this.dataForm.stockId = ""
        this.stockOptions = []
        getStockList({deptId: id}).then(response => {
          if(response.data.code == '0'){
            let resultData = response.data.data
            let stockList = []
            resultData.forEach(item => {
              let stockObj = {
                value: item.id,
                label: item.name
              }
              stockList.push(stockObj)
            })
            this.stockOptions = stockList
            this.dataForm.stockId = resultData[0].id
          }else{
            this.$message.error(response.data.msg)
          }
        })
      },
      // 获取不合格品现象原因列表
      getParentReasonList() {
        this.reasonOption = [];
        getUnqualifiedReasonList({parentId: 0}).then(response => {
          if(response.data.code == '0'){
            let resultData = response.data.data
            let reasonList = []
            resultData.forEach(item => {
              let reasonObj = {
                value: item.id,
                label: item.name
              }
              reasonList.push(reasonObj)
            })
            this.reasonOption = reasonList
          }else{
            this.$message.error(response.data.msg)
          }
        })
      },
      getSecondReasonList(id) {
        this.reasonSecondOption = [];
        this.dataForm.detailList.reason2 = "";
        getUnqualifiedReasonList({parentId: id}).then(response => {
          if(response.data.code == '0'){
            let resultData = response.data.data
            let reasonList = []
            resultData.forEach(item => {
              let reasonObj = {
                value: item.id,
                label: item.name
              }
              reasonList.push(reasonObj)
            })
            this.reasonSecondOption = reasonList
          }else{
            this.$message.error(response.data.msg)
          }
        })
      },
      //  reason2Change事件
      reason2Change(val, row) {
        // console.log(val, row);
      },
      //  条码扫描
      barcodeScan() {
        this.barcodeVisible = true
        this.$nextTick(() => {
          this.$refs.barcodeDialog.init(this.dataForm.outStockId)
        })
      },
      //  条码扫描获取的数据
      getBarcodeGoodsData(data) {
        let obj = { ...data
        }
        obj.goodsId = obj.id
        let result = this.dataForm.detailList.some(item => {
          return item.goodsBarcode == obj.goodsBarcode
        })

        if (result) {
          this.dataForm.detailList.forEach(item => {
            if (item.goodsBarcode == obj.goodsBarcode) {
              item.allocationQuantity += 1
            }
          })
        } else {
          this.dataList.push(obj)
          this.dataForm.detailList.push(obj)
        }
      },
      // 表单提交
      dataFormSubmit() {
        this.ischeck = true
        this.$refs["dataForm"].validate(valid => {
          if (valid) {
            for (let i = 0; i < this.dataList.length; i++) {
              if (!this.dataList[i].reason1) {
                this.ischeck = false
                this.$message.warning('请填写申报不合格品原因')
                return
              }
              if (!this.dataList[i].reason2) {
                this.ischeck = false
                this.$message.warning('请填写申报不合格品现象')
                return
              }
              if (!this.dataList[i].goodsQuantity) {
                this.ischeck = false
                this.$message.warning('请填写申报不合格品数量')
                return
              }
              if (!this.dataList[i].handleMenthod) {
                this.ischeck = false
                this.$message.warning('请填写不合格品处理方式')
                return
              }
            }
            //添加详情里的数据
            this.dataForm.detailList.forEach((item, index) => {
              (item.goodsId = this.dataList[index].goodsId),
              (item.memo = this.dataList[index].memo),
              (item.goodsQuantity = this.dataList[index].goodsQuantity),
              (item.handleMenthod = this.dataList[index].handleMenthod),
              (item.reason1 = this.dataList[index].reason1),
              (item.reason2 = this.dataList[index].reason2),
              (item.goodsName = this.dataList[index].goodsName);
            });
            if (this.dataForm.id) {
              editUnqualifiedObj(this.dataForm).then(response => {
                if(response.data.code == '0'){
                  this.$message.success("修改成功")
                  this.visible = false
                  this.$emit("refreshDataList")
                }else{
                  this.$message.error(response.data.msg)
                }
                this.ischeck = false
              }).catch(() => {
                this.ischeck = false
              })
            } else {
              addUnqualifiedObj(this.dataForm).then(response => {
                if(response.data.code == '0'){
                  this.$message.success("添加成功")
                  this.visible = false
                  this.$emit("refreshDataList")
                }else{
                  this.$message.error(response.data.msg)
                }
                this.ischeck = false
              }).catch(() => {
                this.ischeck = false
              })
            }
          } else {
            this.ischeck = false
          }
        });
      },
      // 按单品添加商品
      openTableList(name) {
        let params = {
          stockId: this.dataForm.stockId
        }
        let data = {
          paramsData: params,
          tableData: this.dataList
        }
        if (this.dataForm.stockId) {
          if (name == "single") {
            this.singleListVisible = true;
            this.$nextTick(() => {
              this.$refs.billOrSingle.init(data);
            });
          } else if (name == "detail") {
            this.detailVisible = true;
            this.$nextTick(() => {
              this.$refs.detailDialog.init(data);
            });
          }
        } else {
          this.$message.warning('请选择申报仓位')
        }

      },
      // 多选表格表格变化事件
      handleSelectionChange(val) {
        this.selectionList = val;
      },
      // 删除商品详情列表中的商品
      delTableData() {
        let list = JSON.parse(JSON.stringify(this.dataList))
        let detailList = JSON.parse(JSON.stringify(this.dataForm.detailList))
        this.selectionList.forEach((item, index) => {
          for (let i = 0; i < list.length; i++) {
            if (JSON.stringify(list[i]) == JSON.stringify(item)) {
              list.splice(i, 1)
              detailList.splice(i, 1)
            }
          }
          this.selectionList = []
        })
        this.dataList = [...list]
        this.dataForm.detailList = [...detailList]
      },
      // bill-list  自定义事件
      getBrandData(data) {
        this.dataList = data
        let list = []
        data.forEach(item => {
          item.goodsCode = item.code || item.goodsCode
          item.goodsName = item.name || item.goodsName
          item.goodsId = item.goodsId || item.id
          delete item.id
          list.push(item)
        })
        this.dataForm.detailList = list

      },
      //  合计
      getSummaries(param) {
        const {
          columns,
          data
        } = param;
        const sums = [];
        columns.forEach((column, index) => {
          if (index === 5) {
            sums[index] = '合计';
            return;
          }
          const values = data.map(item => Number(item[column.property]));
          if (!values.every(value => isNaN(value))) {
            if (index == 6) {
              sums[index] = values.reduce((prev, curr) => {
                const value = Number(curr);
                if (!isNaN(value)) {
                  return prev + curr;
                } else {
                  return prev;
                }
              }, 0)
            }
          }
        });
        return sums;
      }
    }
  };
</script>

<style lang="scss" scoped>
  /deep/ .el-table {
    display: flex;
    flex-direction: column;
  }

  /deep/ .el-table__body-wrapper {
    order: 1;
  }
</style>
